package com.byxy.shop.interceptor;

import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VerifyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String methodName = ((HandlerMethod) handler).getMethod().getName();
//        System.out.println(methodName);
        JSONObject jsonObject = new JSONObject();

        if (methodName.equals("doLogin") || methodName.equals("doRegister")) {
            String verifyCode = request.getParameter("verifyCode");
            String sessionCode = (String) request.getSession().getAttribute("verifyCode");
            if (sessionCode != null) {
                if (verifyCode.equals(sessionCode)) {
                    return true;
                } else {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    response.setStatus(202);
                    jsonObject.put("message", "验证码错误");
                    response.getWriter().append(jsonObject.toString());
                    return false;
                }
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(202);
            jsonObject.put("message", "验证码已过期");
            response.getWriter().append(jsonObject.toString());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
